package com.ndphu.comic.io.processor;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.graphics.Bitmap;

import com.ndphu.comic.gui.activity.MainActivity;
import com.ndphu.comic.io.Utils;
import com.ndphu.comic.model.Book;
import com.ndphu.comic.model.BookEntry;
import com.ndphu.comic.model.Chapter;
import com.ndphu.comic.model.Page;

public class VNSharingProcessor implements BookProcessor {

	private static final String SEARCH_LINK = "http://truyen.vnsharing.net/TimKiemNangCao";

	public static List<BookEntry> searchFromVNSharing(Map<String, String> data) throws Exception {
		List<BookEntry> result = new ArrayList<BookEntry>();
		URL siteUrl = new URL(SEARCH_LINK);
		String baseUrl = SEARCH_LINK.substring(0, SEARCH_LINK.indexOf(siteUrl.getFile()));
		HttpURLConnection conn = (HttpURLConnection) siteUrl.openConnection();
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.setDoInput(true);

		DataOutputStream out = new DataOutputStream(conn.getOutputStream());

		Set keys = data.keySet();
		Iterator keyIter = keys.iterator();
		String content = "";
		for (int i = 0; keyIter.hasNext(); i++) {
			Object key = keyIter.next();
			if (i != 0) {
				content += "&";
			}
			content += key + "=" + URLEncoder.encode(data.get(key), "UTF-8");
		}
		out.writeBytes(content);
		out.flush();
		out.close();
		BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String line = "";
		while ((line = in.readLine()) != null) {
			if (line.contains("<img width=\"120\" height=\"165\" src=")) {
				String cover = line.substring(line.indexOf("src=\"") + 5, line.indexOf("style=") - 2);
				in.readLine();
				line = in.readLine();
				String name = line.substring(line.indexOf(">") + 1, line.lastIndexOf("<"));
				String bookUrl = baseUrl + line.substring(line.indexOf("href") + 6, line.indexOf(">") - 1);
				BookEntry entry = new BookEntry();
				entry.bookName = name;
				entry.bookUrl = bookUrl.replace(" ", "%20");
				entry.bookSource = MainActivity.SOURCE_VNSHARING;
				result.add(entry);
			}
		}
		in.close();

		return result;
	}

	public Book prepareOnlineBook(String bookUrl, boolean complete) throws Exception {
		URL myUrl = new URL(bookUrl);
		URL confirmedUrl = new URL(bookUrl + "?confirm=yes");
		String file = myUrl.getFile();
		String bookName = file.substring(file.lastIndexOf("/") + 1);
		final String baseUrl = bookUrl.substring(0, bookUrl.indexOf(file));
		String line;
		String coverUrl = null;
		String bookDesc = null;
		List<String> chapters = new ArrayList<String>();
		BufferedReader in = new BufferedReader(new InputStreamReader(confirmedUrl.openStream()));
		while ((line = in.readLine()) != null) {
			if (line.contains("<a  href=\"" + file)) {
				chapters.add(line.substring(line.indexOf("\"") + 1, line.lastIndexOf("\"")));
			} else if (coverUrl == null && line.contains("<link rel=\"image_src\" href=")) {
				String tmp = line.substring(line.indexOf("href"));
				coverUrl = tmp.substring(tmp.indexOf("\"") + 1, tmp.lastIndexOf("\""));
			} else if (bookDesc == null && line.contains("</strong><br />")) {
				bookDesc = line.substring(line.indexOf("<br /> ") + 7, line.lastIndexOf("</p>"));
			}
		}
		in.close();

		Book book = new Book();
		book.setName(bookName);
		book.setCover(coverUrl);
		book.setBookDesc(bookDesc);
		int len = chapters.size();
		for (int i = 0; i < len; i++) {
			String chapterUrl = baseUrl + chapters.get(i);
			Chapter chapter = new Chapter();
			chapter.setChapterUrl(chapterUrl);
			chapter.setName(chapters.get(i));
			chapter.setChapterOrder(len - i);
			chapter.setPages(complete ? getChapterPages(chapterUrl) : new ArrayList<Page>());
			book.getChapters().add(chapter);
		}

		Collections.reverse(book.getChapters());

		return book;
	}

	public List<Page> getChapterPages(String chapterUrl) throws IOException {
		List<Page> pages = new ArrayList<Page>();
		URL myUrl = new URL(chapterUrl);
		BufferedReader in = new BufferedReader(new InputStreamReader(myUrl.openStream()));

		String line;
		List<String> picUrlList = new ArrayList<String>();

		while ((line = in.readLine()) != null) {
			if (line.contains("lstImages.push(")) {
				String picUrl = line.replace("lstImages.push(", "").replace("\"", "").replace(");", "").trim().replace(" ", "%20");
				picUrlList.add(picUrl);
			}
		}
		in.close();

		for (int i = 0; i < picUrlList.size(); i++) {
			Page page = new Page();
			page.setLink(picUrlList.get(i));
			page.setPageOrder(i);
			pages.add(page);
		}

		return pages;
	}

	@Override
	public String getBookCoverLink(String bookUrl) throws Exception {
		URL confirmedUrl = new URL(bookUrl + "?confirm=yes");
		String line;
		String coverUrl = null;
		BufferedReader in = new BufferedReader(new InputStreamReader(confirmedUrl.openStream()));
		while ((line = in.readLine()) != null) {
			if (coverUrl == null && line.contains("<link rel=\"image_src\" href=")) {
				String tmp = line.substring(line.indexOf("href"));
				coverUrl = tmp.substring(tmp.indexOf("\"") + 1, tmp.lastIndexOf("\""));
			}
		}
		in.close();
		return coverUrl;
	}

	@Override
	public List<Book> searchOnline(String token) {
		// TODO Auto-generated method stub
		return null;
	}
}
